package org.tnaggs.project.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.tnaggs.project.manager.ContactManager;
import org.tnaggs.project.manager.LeagueManager;
import org.tnaggs.project.manager.LocationManager;
import org.tnaggs.project.manager.TeamManager;
import org.tnaggs.project.model.Game;
import org.tnaggs.project.model.JSONResponse;
import org.tnaggs.project.model.League;
import org.tnaggs.project.model.Team;
import org.tnaggs.project.security.ContactUser;
import org.tnaggs.project.view.GameView;
import org.tnaggs.project.view.TeamView;



@Controller
@RequestMapping("/league")
public class LeagueController {

	@Autowired
	private LeagueManager laxManager;
	
	@Autowired
	private TeamManager teamManager;
	
	@Autowired 
	private LocationManager locManager;
	
	@Autowired 
	private ContactManager conManager;
	
	@RequestMapping(value = "/addLeague.html", method = RequestMethod.POST)
    public String addContact(@ModelAttribute("league")
                            League league, BindingResult result) {
         

        laxManager.createLeague(league);
         
        return "redirect:/index.html";
	}
	
	@RequestMapping(value = "/view.*", method = RequestMethod.GET)
	public ModelAndView viewLeague(@RequestParam("name") String leagueName) {
		 ModelAndView mav = new ModelAndView("viewLeague");
		 
		 String realName= leagueName;
		 try {
			realName = URLDecoder.decode(leagueName, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			System.out.println("Error converting league name: " + e);
		}
		 
		 League league = laxManager.getLeagueRepo().findByName(realName);
		 List<TeamView> teams = new ArrayList<TeamView>();
		 for(Team team :laxManager.getTeams(realName) ) {
			 TeamView view = new TeamView();
			 view.setTeam(team);
			 view.setCoach(conManager.getContact(team.getContactID()));
			 teams.add(view);
		 }
		 
		 mav.addObject("league", league);
		 mav.addObject("teamViews", teams);
		 mav.addObject("teams",laxManager.getTeams(realName));
		 
		 mav.addObject("coaches", laxManager.getAllCoaches());
		 
		 List<Game> games = laxManager.getGames(realName);
		 
		 ArrayList<GameView> goodGames = new ArrayList<GameView>();
		 for(Game game : games) {
			 GameView newView = new GameView();
			 newView.setGame(game);
			 newView.setHomeTeam(teamManager.getTeam(game.getHomeTeamID()));
			 newView.setAwayTeam(teamManager.getTeam(game.getAwayTeamID()));
			 newView.setLocation(locManager.getLocation(game.getLocationID()));
			 goodGames.add(newView);
		 }
		 
		 
		 
		 mav.addObject("games",goodGames);
		 
		 Team team = new Team();
		 team.setLeagueID((int)league.getLeagueId());
		 
		 mav.addObject("commandTeam", team);
		 mav.addObject("commandGame", new Game());
	     mav.addObject("locations",locManager.getAllLocations());
		 
		 ContactUser user = null;
	        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
	        if(principal instanceof UserDetails){
	          user = (ContactUser)principal;
	        } 
	        if(user != null) {
	          mav.addObject("principal", user.getContact());
	        } else {
	          mav.addObject("principal", "anonymous");	
	        }
	        
	        
		 return mav;
	}
	
	public LeagueManager getLaxManager() {
		return laxManager;
	}

	public void setLaxManager(LeagueManager laxManager) {
		this.laxManager = laxManager;
	}
	
	
}
